package com.example.download

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.example.download.databinding.ActivityQuestBinding
import okhttp3.OkHttpClient
import okhttp3.Request
import java.net.HttpURLConnection
import java.net.URL
import kotlin.concurrent.thread

class QuestActivity  : AppCompatActivity() {
    private lateinit var binding: ActivityQuestBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityQuestBinding.inflate(layoutInflater)
        setContentView(binding.root)
        with(binding){
            btnSendRequest.setOnClickListener{
                sendRequestWithOkhttp()
            }
        }
    }
    private fun sendRequestWithOkhttp(){
        thread {
            try {
                val client = OkHttpClient()
                val request = Request.Builder().url("https://www.gov.cn/").build()
                val response = client.newCall(request).execute()
                val responseData = response.body?.string()
                if (responseData != null){
                    showResponse(responseData)
                }
            }catch (e : Exception){
                e.printStackTrace()
            }
        }
    }
    private fun showResponse(response : String){
        runOnUiThread{
            with(binding){
                tvResponse.text = response
            }
        }
    }
}